//
//  AddFileViewController.m
//  SelfDriving
//
//  Created by apple on 16/8/17.
//  Copyright © 2016年 apple. All rights reserved.
//
#import <AVFoundation/AVFoundation.h>
#import "AddFileViewController.h"
#import "EditImageController.h"
#import "VideoCompleteVC.h"
#import "MemberRoamingCell.h"
#import "DynamicMainViewController.h"
#import "ReleaseMainVC.h"
#import "ZLPhotoPickerGroup.h"
#import "CCImageView.h"
#import <QMUIKit/QMUIKit.h>
#import "PhotographCompleteVC.h"
#import "UIView+ShowLineUIView.h"
#import "WCLRecordEncoder.h"
#import "YSHYClipViewController.h"

typedef NS_ENUM(NSInteger,VideoStatus){
    VideoStatusEnded = 0,
    VideoStatusStarted
};

//这里才是点击快拍之后的主界面
@interface AddFileViewController ()<AVCaptureFileOutputRecordingDelegate,UICollectionViewDelegate,UICollectionViewDataSource,BaseCollectionDelegate,VideoCompleteVCDeletage,AVCaptureVideoDataOutputSampleBufferDelegate,AVCaptureAudioDataOutputSampleBufferDelegate,ClipViewControllerDelegate>
{
    CMTime _timeOffset;//录制的偏移CMTime
    CMTime _lastVideo;//记录上一次视频数据文件的CMTime
    CMTime _lastAudio;//记录上一次音频数据文件的CMTime
    
    NSInteger _cx;//视频分辨的宽
    NSInteger _cy;//视频分辨的高
    int _channels;//音频通道
    Float64 _samplerate;//音频采样率
}
@property (atomic, assign) CGFloat maxRecordTime;//录制最长时间
@property (strong, nonatomic) WCLRecordEncoder           *recordEncoder;//录制编码
@property ( strong , nonatomic ) AVCaptureDevice * device;
@property ( strong , nonatomic ) AVCaptureDeviceInput * input;

@property(nonatomic, strong) AVCaptureVideoDataOutput *videoOutput;
@property(nonatomic, strong) AVCaptureAudioDataOutput *audioOutput;
@property(nonatomic, copy) dispatch_queue_t captureQueue;

@property (atomic, assign) BOOL isCapturing;//正在录制
@property (atomic, assign) BOOL isPaused;//是否暂停
@property (atomic, assign) BOOL discont;//是否中断
@property (atomic, assign) CMTime startTime;//开始录制的时间
@property (atomic, assign) CGFloat currentRecordTime;//当前录制时间
@property (atomic, strong) NSString *videoPath;//视频路径

@property ( strong , nonatomic ) AVCaptureStillImageOutput * stillImageOutput;
@property ( strong , nonatomic ) AVCaptureSession * session;

@property ( strong , nonatomic ) AVCaptureVideoPreviewLayer * preview;



#define  gestureMinimumTranslation  20.0

@property (weak, nonatomic) IBOutlet UIButton *nexit;
@property (weak, nonatomic) IBOutlet UIView *videoView;
@property (nonatomic,weak) UIView *focusCircle;
@property (nonatomic,assign) BOOL canSave;
@property (weak, nonatomic) IBOutlet UIView *tkview;
@property (nonatomic,assign) VideoStatus status;
@property (weak, nonatomic) IBOutlet UIButton *tkBtn;
@property (weak, nonatomic) IBOutlet UIButton *psBtn;
@property (weak, nonatomic) IBOutlet BaseCollection *collectionView;
@property (weak, nonatomic) IBOutlet UIView *bootView;
@property (weak, nonatomic) IBOutlet UIButton *spBtn;
@property (weak, nonatomic) IBOutlet UIImageView *tukuImg;
@property (nonatomic,strong) NSMutableArray *videoList;

@property(nonatomic, strong) EditImageController *editImageController;


@property(nonatomic, strong) UIButton *psLeftBtn;
@property(nonatomic, strong) UIButton *psBackBtn;
@property(nonatomic, strong) UIButton *psCenterBtn;
@property(nonatomic, strong) UIButton *psRightBtn;
@property(nonatomic, strong) UIButton *psSumitBtn;

@property(nonatomic, strong) UIButton *spLeftBtn;
@property(nonatomic, strong) UIButton *spBackBtn;
@property(nonatomic, strong) UIButton *spCenterBtn;
@property(nonatomic, strong) UIButton *spRightBtn;
@property(nonatomic, strong) UIButton *spSumitBtn;
@end

@implementation AddFileViewController{
    AVCaptureSession *_captureSession;
    AVCaptureDevice *_videoDevice;
    AVCaptureDevice *_audioDevice;
    AVCaptureDeviceInput *_videoInput;
    AVCaptureDeviceInput *_audioInput;
    
    AVCaptureVideoPreviewLayer *_captureVideoPreviewLayer;
    CGFloat totaTime;
    NSThread *thread;
    int seconds;
    int minus;
    BOOL iszpsp;
    int fileType;//是否是视频，图库，照片
    NSMutableArray *imagedata;
    NSMutableArray *imagedataR;
    
    
    NSArray *Timeimagedata;
    
    UIView *psview;
    UIView *spview;
    UILabel *timelable;//视频倒计时时间
    UIProgressView *pro;//进度条
    
    CameraMoveDirection direction;
    UIImage *iamgeData;
    
    int sizeimg;
    BOOL isyuantu;
    NSMutableArray *tmpimagedata;
    NSString *imgurl;//图库下一步图片路径
    CGPoint startPoint;
    
    UIImage * _clipImage;
    
    
}



//- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
//{
//    [super touchesEnded:touches withEvent:event];
//
//    NSArray *arrayTouches = [[event allTouches] allObjects];
//    NSLog(@"%d--touchesEnded",arrayTouches.count);
//    //    [self reset];
//
//    if (arrayTouches.count == 1) {
//        //结束移动后，需要判断图片是否移动出
//        //        [self reset];
//    }
//}
//-(void)touchesCancelled:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
//    [super touchesCancelled:touches withEvent:event];
//
//    NSArray *arrayTouches = [[event allTouches] allObjects];
//    NSLog(@"%d--touchesCancelled",arrayTouches.count);
//    //    [self reset];
//
//}
#pragma mark 图库刷新
-(void)initData:(int)index{
    index = index -1 ;
    
    if (index == 0) {
        [imagedataR removeAllObjects];
        [imagedata removeAllObjects];
    }
    
    
    NSUInteger ch  = Timeimagedata.count;
    int ta = floor(ch/16);
    if (index > ta ) {
        self.collectionView.footer.hidden = YES;
        return;
    }
    for (int i = 16*index; i<16*(index+1); i++) {
        ALAsset *result;
        @try {
            result = [Timeimagedata objectAtIndex:i];
            if(result == nil){
                continue;
            }
            CGImageRef cimg = [result thumbnail];
            UIImage *img = [UIImage imageWithCGImage:cimg];
            [imagedataR addObject:result];
            [imagedata addObject:img];
            [_collectionView reloadData];
        } @catch (NSException *exception) {
            NSLog(@"%@",exception);
        } @finally {
            
        }
    }
    self.collectionView.footer.hidden = NO;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    
    //记录
    
    switch (self.InType) {
        case 1:
        {
            if ([[NSUserDefaults standardUserDefaults] objectForKey:@"dongtai"]) {
                self.showType = [[[NSUserDefaults standardUserDefaults] objectForKey:@"dongtai"] integerValue];
            } else {
                self.showType = 0;
            }
        }
            break;
        case 2:
        {
            if ([[NSUserDefaults standardUserDefaults] objectForKey:@"chat"]) {
                self.showType = [[[NSUserDefaults standardUserDefaults] objectForKey:@"chat"] integerValue];
            } else {
                self.showType = 1;
            }
        }
            break;
        case 3:
        {
            if ([[NSUserDefaults standardUserDefaults] objectForKey:@"other"]) {
                self.showType = [[[NSUserDefaults standardUserDefaults] objectForKey:@"other"] integerValue];
            } else {
                self.showType = 0;
            }
        }
            break;
        default:
            break;
    }
    
    if (self.hideVideo) {
        //是否隐藏视频拍摄
        _spBtn.hidden = self.hideVideo;
        _tkBtn.frame = CGRectMake(0, 0, SCRE_WIDTH/2.0, 40);
        _psBtn.frame = CGRectMake(SCRE_WIDTH/2.0, 0, SCRE_WIDTH/2.0, 40);
    }
    
    switch (self.showType) {
        case 0:
        {
            [self tukuAction:nil];
        }
            break;
        case 1:
        {
            [self paisheAction:nil];
        }
            break;
        case 2:
        {
            [self shipingAction:nil];
        }
            break;
        default:
            break;
    }    
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];

}

-(void)viewWillDisappear:(BOOL)animated{
    
    switch (self.InType) {
        case 1:
        {
            
            [[NSUserDefaults standardUserDefaults] setObject:@(self.showType) forKey:@"dongtai"];
        }
            break;
        case 2:
        {
            [[NSUserDefaults standardUserDefaults] setObject:@(self.showType) forKey:@"chat"];
        }
            break;
        case 3:
        {
            [[NSUserDefaults standardUserDefaults] setObject:@(self.showType) forKey:@"other"];
        }
            break;
        default:
            break;
    }
    [AppDelegate shareDelegate].islod = NO;
}


-(void)dtPhotoComplete:(NSNotification *)not{
    
}


-(void)dtbackaction:(NSNotification *)not{
    [AppDelegate shareDelegate].dttype = 0;
    [self dismissViewControllerAnimated:YES completion:nil];
    [self.navigationController popViewControllerAnimated:YES];
}
//xhw2018-1-15加:之前如果是点击快拍进入到这个ctrl,里面的intype为nil;
//- (NSInteger)InType {
//    if (!_InType) {
//        return 1;
//    }
//    return _InType;
//
//}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    //xhw2018-1-16:
    if (!_InType) {
        _InType = 4;
    }
    
    Timeimagedata = [[[AppDelegate shareDelegate].imagData1 reverseObjectEnumerator] allObjects];
    imagedataR = [[NSMutableArray alloc]init];
    imagedata = [[NSMutableArray alloc]init];
    ALAsset *result = [Timeimagedata firstObject];
    ALAssetRepresentation *presentation = [result defaultRepresentation];
    CGImageRef resolutionImg = [presentation fullResolutionImage];
    UIImage *img = [UIImage imageWithCGImage:resolutionImg scale:1 orientation:(NSInteger)presentation.orientation];
    imgurl = [presentation.url absoluteString];
    iamgeData = img;
    self.tukuImg.image = img;
    isyuantu = NO;
    
    
    [[NSNotificationCenter defaultCenter]
     addObserver:self
     selector:@selector(dtbackaction:)
     name:@"dtbackaction"
     object:nil];
    
    [[NSNotificationCenter defaultCenter]
     addObserver:self
     selector:@selector(dtPhotoComplete:)
     name:@"DTPhotoComplete"
     object:nil];
    
    // 创建
    [self getAuthorization];
    [self addGenstureRecognizer];
    totaTime = 10;
    
    _tkBtn.selected = YES;
    
    self.maxRecordTime = 10;
    
    [self initViewtk];
}
- ( CameraMoveDirection )determineCameraDirectionIfNeeded:( CGPoint )translation

{
    if (direction != kCameraMoveDirectionNone)
        return direction;
    
    if (fabs(translation.x) > gestureMinimumTranslation)
        
    {
        
        BOOL gestureHorizontal = NO;
        
        if (translation.y == 0.0 )
            
            gestureHorizontal = YES;
        
        else
            
            gestureHorizontal = (fabs(translation.x / translation.y) > 5.0 );
        
        if (gestureHorizontal)
            
        {
            
            if (translation.x > 0.0 )
                
                return kCameraMoveDirectionRight;
            
            else
                
                return kCameraMoveDirectionLeft;
            
        }
        
    }
    
    // determine if vertical swipe only if you meet some minimum velocity
    
    else if (fabs(translation.y) > gestureMinimumTranslation)
        
    {
        
        BOOL gestureVertical = NO;
        
        if (translation.x == 0.0 )
            
            gestureVertical = YES;
        
        else
            
            gestureVertical = (fabs(translation.y / translation.x) > 5.0 );
        
        if (gestureVertical)
            
        {
            if (translation.y > 0.0 )
                return kCameraMoveDirectionDown;
            else
                return kCameraMoveDirectionUp;
        }
    }
    return direction;
}
#pragma mark 滑动照片或者视频
-(void)qiehuanship:(UIPanGestureRecognizer *)cgr{
    CGPoint translation = [cgr translationInView: _videoView];
    if (cgr.state == UIGestureRecognizerStateBegan )
    {
        direction = kCameraMoveDirectionNone;
    }else  if (cgr.state == UIGestureRecognizerStateChanged&& direction == kCameraMoveDirectionNone)
    {
        direction = [ self determineCameraDirectionIfNeeded:translation];
        if (direction == kCameraMoveDirectionRight) {
            fileType ++;
        }
        if (direction == kCameraMoveDirectionLeft) {
            fileType --;
        }
    }
    
    if(fileType==4){
        fileType = 3;
    }
    if(fileType<1){
        fileType = 1;
    }
    _collectionView.hidden = YES;
    _tukuImg.hidden = YES;
    
    _tkview.hidden = YES;
    if(psview){
        psview.hidden = YES;
    }
    if(spview){
        spview.hidden = YES;
    }
    if(fileType == 1 ){
        [self tukuAction:nil];
    }
    if(fileType == 2 ){
        [self paisheAction:nil];
    }
    if(fileType == 3 ){
        [self shipingAction:nil];
    }
}
#pragma mark 图库
- (IBAction)tukuAction:(UIButton *)sender {
    [self hidePZSubmitBtns];
    [self cancelAction];
    
    _nexit.hidden = NO;
    _tkview.hidden = NO;
    _collectionView.hidden = YES;
    if(psview){
        psview.hidden = YES;
    }
    if(spview){
        spview.hidden = YES;
    }
    _collectionView.hidden = NO;
    _tkBtn.selected = YES;
    _tkBtn.showBottomLine = YES;
    //9月15号改:bug（11579）底部线条细一点，之前是3改为2
    _tkBtn.lineWidth = 0.5;
    _tkBtn.lineColor = [UIColor greenColor];
    _psBtn.selected = NO;
    _psBtn.showBottomLine = NO;
    _psBtn.lineWidth = 0.5;
    _psBtn.lineColor = [UIColor greenColor];
    _spBtn.selected = NO;
    _spBtn.showBottomLine = NO;
    _spBtn.lineWidth = 0.5;
    _spBtn.lineColor = [UIColor greenColor];
    _tukuImg.hidden = NO;
    self.showType = 0;
}
#pragma  mark 拍摄
- (IBAction)paisheAction:(UIButton *)sender {
    
    [self hidePZSubmitBtns];
    [self cancelAction];
    _collectionView.hidden = YES;
    _tukuImg.hidden = YES;
    _nexit.hidden = YES;
    _tkview.hidden = YES;
    _nexit.hidden = YES;
    if(psview){
        psview.hidden = YES;
    }
    if(spview){
        spview.hidden = YES;
    }
    _tkBtn.selected = NO;
    _tkBtn.showBottomLine = NO;
    _tkBtn.lineWidth = 0.5;
    _tkBtn.lineColor = [UIColor greenColor];
    _psBtn.selected = YES;
    _psBtn.showBottomLine = YES;
    _psBtn.lineWidth = 0.5;
    _psBtn.lineColor = [UIColor greenColor];
    _spBtn.selected = NO;
    _spBtn.showBottomLine = NO;
    _spBtn.lineWidth = 0.5;
    _spBtn.lineColor = [UIColor greenColor];
    self.showType = 1;
    if(!psview){
        [psview removeFromSuperview];
        psview = [[UIView alloc]initWithFrame:CGRectMake(0, (SCRE_WIDTH+54), SCRE_WIDTH, SCRE_HEIGHT-(SCRE_WIDTH + 54)-40)];
        psview.backgroundColor = [UIColor colorWithWhite:0 alpha:0.2];
        [self.view addSubview:psview];
        //切换
        _psLeftBtn = [[UIButton alloc]initWithFrame:CGRectMake(30, psview.frame.size.height/2-46/2, 46, 46)];
        [_psLeftBtn setImage:[UIImage imageNamed:@"pzqie"] forState:UIControlStateNormal];
        _psLeftBtn.backgroundColor = [UIColor colorWithWhite:1 alpha:0.3];
        _psLeftBtn.layer.cornerRadius = 23;
        [_psLeftBtn addTarget:self action:@selector(qiehuanAction:) forControlEvents:UIControlEventTouchUpInside];
        [psview addSubview:_psLeftBtn];
        
        //返回重拍按钮
        _psBackBtn = [[UIButton alloc]initWithFrame:CGRectMake(30, psview.frame.size.height/2-46/2, 46, 46)];
        [_psBackBtn setImage:[UIImage imageNamed:@"pzcx"] forState:UIControlStateNormal];
        _psBackBtn.backgroundColor = [UIColor colorWithWhite:1 alpha:0.3];
        _psBackBtn.layer.cornerRadius = 23;
        _psBackBtn.hidden = YES;
        [_psBackBtn addTarget:self action:@selector(cancelPZ) forControlEvents:UIControlEventTouchUpInside];
        [psview addSubview:_psBackBtn];
        
        //拍照
        _psCenterBtn = [[UIButton alloc] initWithFrame:CGRectMake(psview.frame.size.width/2-78/2, psview.frame.size.height/2-78/2, 78, 78)];
        [_psCenterBtn setImage:[UIImage qmui_imageWithColor:UIColorGreen size:CGSizeMake(70, 70) cornerRadius:35] forState:UIControlStateNormal];
        _psCenterBtn.contentMode = UIViewContentModeCenter;
        _psCenterBtn.layer.borderColor = UIColorWhite.CGColor;
        _psCenterBtn.layer.borderWidth = 2;
        _psCenterBtn.layer.cornerRadius = 39;
        _psCenterBtn.clipsToBounds = YES;
        [_psCenterBtn addTarget:self action:@selector(StartShootingAction:) forControlEvents:UIControlEventTouchUpInside];
        [psview addSubview:_psCenterBtn];
        
        //闪光
        _psRightBtn = [[UIButton alloc]initWithFrame:CGRectMake(SCRE_WIDTH-76, psview.frame.size.height/2-46/2, 46, 46)];
        _psRightBtn.backgroundColor = [UIColor colorWithWhite:1 alpha:0.3];
        _psRightBtn.layer.cornerRadius = 23;
        [_psRightBtn setImage:[UIImage imageNamed:@"pzsan"] forState:UIControlStateNormal];
        [_psRightBtn addTarget:self action:@selector(shanguangAction:) forControlEvents:UIControlEventTouchUpInside];
        _psRightBtn.clipsToBounds = YES;
        [psview addSubview:_psRightBtn];
        
        //确认已拍照片
        _psSumitBtn = [[UIButton alloc]initWithFrame:CGRectMake(SCRE_WIDTH-76, psview.frame.size.height/2-46/2, 46, 46)];
        _psSumitBtn.backgroundColor = [UIColor colorWithWhite:1 alpha:0.3];
        _psSumitBtn.layer.cornerRadius = 23;
        [_psSumitBtn setImage:[UIImage imageNamed:@"pzwc"] forState:UIControlStateNormal];
        [_psSumitBtn addTarget:self action:@selector(completePZ) forControlEvents:UIControlEventTouchUpInside];
        _psSumitBtn.clipsToBounds = YES;
        _psSumitBtn.hidden = YES;
        [psview addSubview:_psSumitBtn];
        
    }else{
        psview.hidden = NO;
    }
    
}

#pragma mark 视频
- (IBAction)shipingAction:(id)sender {
    [self hidePZSubmitBtns];
    [self cancelAction];
    
    _collectionView.hidden = YES;
    _tukuImg.hidden = YES;
    _tkview.hidden = YES;
    _nexit.hidden = YES;
    self.showType = 2;
    if(psview){
        psview.hidden = YES;
    }
    if(spview){
        spview.hidden = YES;
    }
    _tkBtn.selected = NO;
    _tkBtn.showBottomLine = NO;
    _tkBtn.lineWidth = 0.5;
    _tkBtn.lineColor = [UIColor greenColor];
    _psBtn.selected = NO;
    _psBtn.showBottomLine = NO;
    _psBtn.lineWidth = 0.5;
    _psBtn.lineColor = [UIColor greenColor];
    _spBtn.selected = YES;
    _spBtn.showBottomLine = YES;
    _spBtn.lineWidth = 0.5;
    _spBtn.lineColor = [UIColor greenColor];
    [spview removeFromSuperview];
    
    spview = [[UIView alloc]initWithFrame:CGRectMake(0, (SCRE_WIDTH+54), SCRE_WIDTH, SCRE_HEIGHT-(SCRE_WIDTH + 54)-40)];
    spview.backgroundColor = [UIColor colorWithWhite:0 alpha:0.2];
    [self.view addSubview:spview];
    //切换
    _spLeftBtn = [[UIButton alloc]initWithFrame:CGRectMake(30, spview.frame.size.height/2-46/2, 46, 46)];
    [_spLeftBtn setImage:[UIImage imageNamed:@"pzqie"] forState:UIControlStateNormal];
    _spLeftBtn.backgroundColor = [UIColor colorWithWhite:1 alpha:0.3];
    _spLeftBtn.layer.cornerRadius = 23;
    [_spLeftBtn addTarget:self action:@selector(qiehuanAction:) forControlEvents:UIControlEventTouchUpInside];
    [spview addSubview:_spLeftBtn];
    
    //返回重拍按钮
    _spBackBtn = [[UIButton alloc]initWithFrame:CGRectMake(30, spview.frame.size.height/2-46/2, 46, 46)];
    [_spBackBtn setImage:[UIImage imageNamed:@"pzcx"] forState:UIControlStateNormal];
    _spBackBtn.backgroundColor = [UIColor colorWithWhite:1 alpha:0.3];
    _spBackBtn.layer.cornerRadius = 23;
    _spBackBtn.hidden = YES;
    [_spBackBtn addTarget:self action:@selector(cancelAction) forControlEvents:UIControlEventTouchUpInside];
    [spview addSubview:_spBackBtn];
    
    //闪光
    _spRightBtn = [[UIButton alloc]initWithFrame:CGRectMake(SCRE_WIDTH-76, spview.frame.size.height/2-46/2, 46, 46)];
    _spRightBtn.layer.cornerRadius = 23;
    _spRightBtn.backgroundColor = [UIColor colorWithWhite:1 alpha:0.3];
    [_spRightBtn setImage:[UIImage imageNamed:@"pzsan"] forState:UIControlStateNormal];
    [_spRightBtn addTarget:self action:@selector(shanguangAction:) forControlEvents:UIControlEventTouchUpInside];
    [spview addSubview:_spRightBtn];
    
    //拍照
    _spCenterBtn = [[UIButton alloc] initWithFrame:CGRectMake(spview.frame.size.width/2-78/2, spview.frame.size.height/2-78/2, 78, 78)];
    [_spCenterBtn setImage:[UIImage qmui_imageWithColor:UIColorRed size:CGSizeMake(70, 70) cornerRadius:35] forState:UIControlStateNormal];
    _spCenterBtn.contentMode = UIViewContentModeCenter;
    _spCenterBtn.layer.borderColor = UIColorWhite.CGColor;
    _spCenterBtn.layer.borderWidth = 2;
    _spCenterBtn.layer.cornerRadius = 39;
    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(kaishipaisAction:)];
    [_spCenterBtn addGestureRecognizer:longPress];
    [spview addSubview:_spCenterBtn];
    
    
    //确认已拍视频
    _spSumitBtn = [[UIButton alloc]initWithFrame:CGRectMake(SCRE_WIDTH-76, spview.frame.size.height/2-46/2, 46, 46)];
    _spSumitBtn.backgroundColor = [UIColor colorWithWhite:1 alpha:0.3];
    _spSumitBtn.layer.cornerRadius = 23;
    [_spSumitBtn setImage:[UIImage imageNamed:@"pzwc"] forState:UIControlStateNormal];
    [_spSumitBtn addTarget:self action:@selector(completeAction) forControlEvents:UIControlEventTouchUpInside];
    _spSumitBtn.clipsToBounds = YES;
    _spSumitBtn.hidden = YES;
    [spview addSubview:_spSumitBtn];
    
    
    timelable = [[UILabel alloc]initWithFrame:CGRectMake(SCRE_WIDTH - 65, 20, 45, 20)];
    timelable.textColor = [UIColor whiteColor];
    timelable.layer.borderColor =[UIColor whiteColor].CGColor;
    timelable.layer.borderWidth = 1;
    timelable.layer.cornerRadius = 4;
    timelable.textAlignment = NSTextAlignmentCenter;
    timelable.font = [UIFont systemFontOfSize:13];
    timelable.text = @"0秒";
    [spview addSubview:timelable];
    //进度条
    pro = [[UIProgressView alloc]initWithFrame:CGRectMake(0,0, SCRE_WIDTH, 8)];
    pro.progressTintColor=[UIColor greenColor];
    [spview addSubview:pro];
    spview.hidden = NO;
    
}

#pragma mark  图库
-(void)initViewtk{
    _collectionView.frame = CGRectMake(0, SCRE_HEIGHT -(SCRE_HEIGHT/3), SCRE_WIDTH, SCRE_HEIGHT/3);
    _collectionView.hidden = NO;
    _collectionView.delegate = self;
    _collectionView.bdelegate = self;
    
}
#pragma  mark uicollectionViewDeleage
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    NSUInteger cout = imagedata.count;
    return cout;
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    MemberRoamingCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"MemberRoamingCell" forIndexPath:indexPath];
    UIImageView *head = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, cell.frame.size.width, cell.frame.size.height)];
    head.clipsToBounds = YES;
    if([[cell.contentView.subviews lastObject] isKindOfClass:[UIView class]]){
        [[cell.contentView.subviews lastObject] removeFromSuperview];
    }
    id s = [imagedata objectAtIndex:indexPath.row];
    if ([s isKindOfClass:[UIImage class]]) {
        head.image = s;
        [cell.contentView addSubview:head];
    }
    return cell;
}
-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return 0.f;
}
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(0,1, 1, 1);
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    CGSize size = CGSizeMake(SCRE_WIDTH/4-3,SCRE_WIDTH/4);
    return size;
}
//xhw2018-1-2加的注释:选择图库中一张照片之后的action
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if (self.InType == 2) {
        if (self.delegate && [self.delegate respondsToSelector:@selector(didGetImage:)]) {
            ALAsset *result = [imagedataR objectAtIndex:indexPath.item];
            ALAssetRepresentation *presentation = [result defaultRepresentation];
            UIImage *img = [UIImage imageWithCGImage:presentation.fullScreenImage];
            [self.delegate didGetImage:img];
            [self dismissViewControllerAnimated:YES completion:nil];
            return;
        }
    }
    ALAsset *result = [imagedataR objectAtIndex:indexPath.item];
    ALAssetRepresentation *presentation = [result defaultRepresentation];
    UIImage *img = [UIImage imageWithCGImage:presentation.fullScreenImage];
    imgurl = [presentation.url absoluteString];
    iamgeData = img;
    self.tukuImg.image = img;
    isyuantu = NO;
}
#pragma mark  下一步
- (IBAction)nexitAction:(id)sender {
    
    if(iamgeData != nil){
        ALAssetsLibrary *assetLibrary = [[ALAssetsLibrary alloc] init];
        NSURL *url = [NSURL URLWithString:imgurl];
        [assetLibrary assetForURL:url resultBlock:^(ALAsset *asset)  {
            //        UIImage *image=[UIImage imageWithCGImage:asset.aspectRatioThumbnail];
            ALAssetRepresentation *assetRepresentation = [asset defaultRepresentation]; //大图片
            UIImage *image = [UIImage imageWithCGImage:assetRepresentation.fullScreenImage];
            [AppDelegate shareDelegate].dttype = 1;
            self.editImageController.image = image;
            self.editImageController.backVCCount = 1;
            self.editImageController.presentVC = self; //xhw2018-1-22加
            //(xhw11月24号加)
            self.editImageController.InType = self.InType;
            [self presentViewController:self.editImageController animated:YES completion:nil];
        }failureBlock:^(NSError *error) {
            NSLog(@"error=%@",error);
        }];
    }
}

#pragma  mark （按住开始拍摄）
- (void)kaishipaisAction:(UIGestureRecognizer *)sender {
    
    
    if(sender.state == UIGestureRecognizerStateBegan){
        
        if (_currentRecordTime == 0) {
            //开始录制
            [self startCapture];
        } else {
            //继续
            [self resumeCapture];
        }
    }
    if(sender.state == UIGestureRecognizerStateEnded){
        
        if (_currentRecordTime < _maxRecordTime) {
            //暂停
            [self pauseCapture];
        } else {
            //结束
            [self stopCaptureHandler:^(UIImage *movieImage) {
                [self showCompleteVideo];
            }];
        }
        
    }
}

//获取授权
- (void)getAuthorization
{
    /*
     AVAuthorizationStatusNotDetermined = 0,// 未进行授权选择
     
     AVAuthorizationStatusRestricted,　　　　// 未授权，且用户无法更新，如家长控制情况下
     
     AVAuthorizationStatusDenied,　　　　　　 // 用户拒绝App使用
     
     AVAuthorizationStatusAuthorized,　　　　// 已授权，可使用
     */
    //此处获取摄像头授权
    switch ([AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo])
    {
        case AVAuthorizationStatusAuthorized:       //已授权，可使用    The client is authorized to access the hardware supporting a media type.
        {
            NSLog(@"授权摄像头使用成功");
            [self setupAVCaptureInfo];
            break;
        }
        case AVAuthorizationStatusNotDetermined:    //未进行授权选择     Indicates that the user has not yet made a choice regarding whether the client can access the hardware.
        {
            //则再次请求授权
            [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
                if(granted){    //用户授权成功
                    [self setupAVCaptureInfo];
                    return;
                } else {        //用户拒绝授权
                    [self pop];
                    [self showMsgWithTitle:@"出错了" andContent:@"用户拒绝授权摄像头的使用权,返回上一页.请打开\n设置-->隐私/通用等权限设置"];
                    return;
                }
            }];
            break;
        }
        default:                                    //用户拒绝授权/未授权
        {
            [self pop];
            [self showMsgWithTitle:@"出错了" andContent:@"拒绝授权,返回上一页.请检查下\n设置-->隐私/通用等权限设置"];
            break;
        }
    }
    
}

- (void)setupAVCaptureInfo
{
    [self addSession];
    
    [_captureSession beginConfiguration];
    
    [self addVideo];
    [self addAudio];
    [self addPreviewLayer];
    
    [_captureSession commitConfiguration];
    
    //开启会话-->注意,不等于开始录制
    [_captureSession startRunning];
    
}

- (void)addSession
{
    _captureSession = [[AVCaptureSession alloc] init];
    [ _captureSession setSessionPreset : AVCaptureSessionPresetHigh ];
    //设置视频分辨率
    /*  通常支持如下格式
     (
     AVAssetExportPresetLowQuality,
     AVAssetExportPreset960x540,
     AVAssetExportPreset640x480,
     AVAssetExportPresetMediumQuality,
     AVAssetExportPreset1920x1080,
     AVAssetExportPreset1280x720,
     AVAssetExportPresetHighestQuality,
     AVAssetExportPresetAppleM4A
     )
     */
    //注意,这个地方设置的模式/分辨率大小将影响你后面拍摄照片/视频的大小,
    if ([_captureSession canSetSessionPreset:AVAssetExportPresetHighestQuality]) {
        [_captureSession setSessionPreset:AVAssetExportPresetHighestQuality];
    }
    
    if ([ _captureSession canAddOutput : self.stillImageOutput ])
    {
        [ _captureSession addOutput :  self.stillImageOutput ];
    }
}

- (void)addVideo
{
    // 获取摄像头输入设备， 创建 AVCaptureDeviceInput 对象
    /* MediaType
     AVF_EXPORT NSString *const AVMediaTypeVideo                 NS_AVAILABLE(10_7, 4_0);       //视频
     AVF_EXPORT NSString *const AVMediaTypeAudio                 NS_AVAILABLE(10_7, 4_0);       //音频
     AVF_EXPORT NSString *const AVMediaTypeText                  NS_AVAILABLE(10_7, 4_0);
     AVF_EXPORT NSString *const AVMediaTypeClosedCaption         NS_AVAILABLE(10_7, 4_0);
     AVF_EXPORT NSString *const AVMediaTypeSubtitle              NS_AVAILABLE(10_7, 4_0);
     AVF_EXPORT NSString *const AVMediaTypeTimecode              NS_AVAILABLE(10_7, 4_0);
     AVF_EXPORT NSString *const AVMediaTypeMetadata              NS_AVAILABLE(10_8, 6_0);
     AVF_EXPORT NSString *const AVMediaTypeMuxed                 NS_AVAILABLE(10_7, 4_0);
     */
    
    /* AVCaptureDevicePosition
     typedef NS_ENUM(NSInteger, AVCaptureDevicePosition) {
     AVCaptureDevicePositionUnspecified         = 0,
     AVCaptureDevicePositionBack                = 1,            //后置摄像头
     AVCaptureDevicePositionFront               = 2             //前置摄像头
     } NS_AVAILABLE(10_7, 4_0) __TVOS_PROHIBITED;
     */
    _videoDevice = [self deviceWithMediaType:AVMediaTypeVideo preferringPosition:AVCaptureDevicePositionBack];
    
    [self addVideoInput];
    [self addMovieOutput];
}

- (void)addVideoInput
{
    NSError *videoError;
    
    // 视频输入对象
    // 根据输入设备初始化输入对象，用户获取输入数据
    _videoInput = [[AVCaptureDeviceInput alloc] initWithDevice:_videoDevice error:&videoError];
    if (videoError) {
        NSLog(@"---- 取得摄像头设备时出错 ------ %@",videoError);
        return;
    }
    
    // 将视频输入对象添加到会话 (AVCaptureSession) 中
    if ([_captureSession canAddInput:_videoInput]) {
        [_captureSession addInput:_videoInput];
    }
    
}

- (void)addMovieOutput
{
    // 拍摄视频输出对象
    // 初始化输出设备对象，用户获取输出数据
    
    if ([_captureSession canAddOutput:self.videoOutput]) {
        [_captureSession addOutput:self.videoOutput];
        AVCaptureConnection *captureConnection = [self.videoOutput connectionWithMediaType:AVMediaTypeVideo];
        
        //设置视频旋转方向
        /*
         typedef NS_ENUM(NSInteger, AVCaptureVideoOrientation) {
         AVCaptureVideoOrientationPortrait           = 1,
         AVCaptureVideoOrientationPortraitUpsideDown = 2,
         AVCaptureVideoOrientationLandscapeRight     = 3,
         AVCaptureVideoOrientationLandscapeLeft      = 4,
         } NS_AVAILABLE(10_7, 4_0) __TVOS_PROHIBITED;
         */
        if ([captureConnection isVideoOrientationSupported]) {
            [captureConnection setVideoOrientation:AVCaptureVideoOrientationPortrait];
        }
        //
        //        // 视频稳定设置
        //        if ([captureConnection isVideoStabilizationSupported]) {
        //            captureConnection.preferredVideoStabilizationMode = AVCaptureVideoStabilizationModeAuto;
        //        }
        //        captureConnection.videoScaleAndCropFactor = captureConnection.videoMaxScaleAndCropFactor;
        
    }
    //设置视频的分辨率
    _cx = 720;
    _cy = 1280;
}

- (void)addAudio
{
    NSError *audioError;
    // 添加一个音频输入设备
    _audioDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeAudio];
    //  音频输入对象
    _audioInput = [[AVCaptureDeviceInput alloc] initWithDevice:_audioDevice error:&audioError];
    if (audioError) {
        NSLog(@"取得录音设备时出错 ------ %@",audioError);
        return;
    }
    // 将音频输入对象添加到会话 (AVCaptureSession) 中
    if ([_captureSession canAddInput:_audioInput]) {
        [_captureSession addInput:_audioInput];
    }
    
    // 将音频输出对象添加到会话 (AVCaptureSession) 中
    if ([_captureSession canAddOutput:self.audioOutput]) {
        [_captureSession addOutput:self.audioOutput];
        
        [self.audioOutput connectionWithMediaType:AVMediaTypeAudio];
    }
    
    
}

- (void)addPreviewLayer
{
    
    [self.view layoutIfNeeded];
    // 通过会话 (AVCaptureSession) 创建预览层
    _captureVideoPreviewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:_captureSession];
    _captureVideoPreviewLayer.frame = CGRectMake(0, 0, SCRE_WIDTH, SCRE_HEIGHT);
    /* 填充模式
     Options are AVLayerVideoGravityResize, AVLayerVideoGravityResizeAspect and AVLayerVideoGravityResizeAspectFill. AVLayerVideoGravityResizeAspect is default.
     */
    //有时候需要拍摄完整屏幕大小的时候可以修改这个
    _captureVideoPreviewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    // 如果预览图层和视频方向不一致,可以修改这个
    //    _captureVideoPreviewLayer.connection.videoOrientation = [_movieOutput connectionWithMediaType:AVMediaTypeVideo].videoOrientation;
    //    _captureVideoPreviewLayer.position = CGPointMake(self.view.frame.size.width*0.5,self.view.frame.size.height*0.5);
    // 显示在视图表面的图层
    [_videoView.layer addSublayer:_captureVideoPreviewLayer];
}

#pragma mark pop

-(void)pop
{
    if (self.navigationController) {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (void)showMsgWithTitle:(NSString *)title andContent:(NSString *)content
{
    [[[UIAlertView alloc] initWithTitle:title message:content delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil] show];
}

#pragma mark 获取摄像头-->前/后

- (AVCaptureDevice *)deviceWithMediaType:(NSString *)mediaType preferringPosition:(AVCaptureDevicePosition)position
{
    NSArray *devices = [AVCaptureDevice devicesWithMediaType:mediaType];
    AVCaptureDevice *captureDevice = devices.firstObject;
    
    for ( AVCaptureDevice *device in devices ) {
        if ( device.position == position ) {
            captureDevice = device;
            break;
        }
    }
    
    return captureDevice;
}
/**
 *  添加点按手势，点按时聚焦
 */
-(void)addGenstureRecognizer{
    
    UITapGestureRecognizer *singleTapGesture=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(singleTap:)];
    singleTapGesture.numberOfTapsRequired = 1;
    singleTapGesture.delaysTouchesBegan = YES;
    
    UITapGestureRecognizer *doubleTapGesture=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(doubleTap:)];
    doubleTapGesture.numberOfTapsRequired = 2;
    doubleTapGesture.delaysTouchesBegan = YES;
    
    [singleTapGesture requireGestureRecognizerToFail:doubleTapGesture];
    [self.videoView addGestureRecognizer:singleTapGesture];
    [self.videoView addGestureRecognizer:doubleTapGesture];
}

-(void)singleTap:(UITapGestureRecognizer *)tapGesture{
    
    CGPoint point= [tapGesture locationInView:self.videoView];
    //将UI坐标转化为摄像头坐标,摄像头聚焦点范围0~1
    CGPoint cameraPoint= [_captureVideoPreviewLayer captureDevicePointOfInterestForPoint:point];
    [self setFocusCursorAnimationWithPoint:point];
    
    [self changeDevicePropertySafety:^(AVCaptureDevice *captureDevice) {
        
        /*
         @constant AVCaptureFocusModeLocked 锁定在当前焦距
         Indicates that the focus should be locked at the lens' current position.
         
         @constant AVCaptureFocusModeAutoFocus 自动对焦一次,然后切换到焦距锁定
         Indicates that the device should autofocus once and then change the focus mode to AVCaptureFocusModeLocked.
         
         @constant AVCaptureFocusModeContinuousAutoFocus 当需要时.自动调整焦距
         Indicates that the device should automatically focus when needed.
         */
        //聚焦
        if ([captureDevice isFocusModeSupported:AVCaptureFocusModeContinuousAutoFocus]) {
            [captureDevice setFocusMode:AVCaptureFocusModeContinuousAutoFocus];
            NSLog(@"聚焦模式修改为%zd",AVCaptureFocusModeContinuousAutoFocus);
        }else{
            NSLog(@"聚焦模式修改失败");
        }
        
        //聚焦点的位置
        if ([captureDevice isFocusPointOfInterestSupported]) {
            [captureDevice setFocusPointOfInterest:cameraPoint];
        }
        
        /*
         @constant AVCaptureExposureModeLocked  曝光锁定在当前值
         Indicates that the exposure should be locked at its current value.
         
         @constant AVCaptureExposureModeAutoExpose 曝光自动调整一次然后锁定
         Indicates that the device should automatically adjust exposure once and then change the exposure mode to AVCaptureExposureModeLocked.
         
         @constant AVCaptureExposureModeContinuousAutoExposure 曝光自动调整
         Indicates that the device should automatically adjust exposure when needed.
         
         @constant AVCaptureExposureModeCustom 曝光只根据设定的值来
         Indicates that the device should only adjust exposure according to user provided ISO, exposureDuration values.
         
         */
        //曝光模式
        if ([captureDevice isExposureModeSupported:AVCaptureExposureModeAutoExpose]) {
            [captureDevice setExposureMode:AVCaptureExposureModeAutoExpose];
        }else{
            NSLog(@"曝光模式修改失败");
        }
        
        //曝光点的位置
        if ([captureDevice isExposurePointOfInterestSupported]) {
            [captureDevice setExposurePointOfInterest:cameraPoint];
        }
    }];
}
//设置焦距
-(void)doubleTap:(UITapGestureRecognizer *)tapGesture{
    
    [self changeDevicePropertySafety:^(AVCaptureDevice *captureDevice) {
        if (captureDevice.videoZoomFactor == 1.0) {
            CGFloat current = 1.5;
            if (current < captureDevice.activeFormat.videoMaxZoomFactor) {
                [captureDevice rampToVideoZoomFactor:current withRate:10];
            }
        }else{
            [captureDevice rampToVideoZoomFactor:1.0 withRate:10];
        }
    }];
}

//光圈动画
-(void)setFocusCursorAnimationWithPoint:(CGPoint)point{
    self.focusCircle.center = point;
    self.focusCircle.transform = CGAffineTransformIdentity;
    self.focusCircle.alpha = 1.0;
    [UIView animateWithDuration:0.5 animations:^{
        self.focusCircle.transform=CGAffineTransformMakeScale(0.5, 0.5);
        self.focusCircle.alpha = 0.0;
    }];
}

//光圈
- (UIView *)focusCircle{
    if (!_focusCircle) {
        UIView *focusCircle = [[UIView alloc] init];
        focusCircle.frame = CGRectMake(0, 0, 100, 100);
        focusCircle.layer.borderColor = [UIColor orangeColor].CGColor;
        focusCircle.layer.borderWidth = 2;
        focusCircle.layer.cornerRadius = 50;
        focusCircle.layer.masksToBounds =YES;
        _focusCircle = focusCircle;
        [self.videoView addSubview:focusCircle];
    }
    return _focusCircle;
}

//切换摄像头(前置还是后置)
- (IBAction)qiehuanAction:(UIButton *)sender {
    switch (_videoDevice.position) {
        case AVCaptureDevicePositionBack:
            _videoDevice = [self deviceWithMediaType:AVMediaTypeVideo preferringPosition:AVCaptureDevicePositionFront];
            break;
        case AVCaptureDevicePositionFront:
            _videoDevice = [self deviceWithMediaType:AVMediaTypeVideo preferringPosition:AVCaptureDevicePositionBack];
            break;
        default:
            return;
            break;
    }
    
    [self changeDevicePropertySafety:^(AVCaptureDevice *captureDevice) {
        NSError *error;
        AVCaptureDeviceInput *newVideoInput = [[AVCaptureDeviceInput alloc] initWithDevice:_videoDevice error:&error];
        
        if (newVideoInput != nil) {
            //必选先 remove 才能询问 canAdd
            [_captureSession removeInput:_videoInput];
            if ([_captureSession canAddInput:newVideoInput]) {
                [_captureSession addInput:newVideoInput];
                _videoInput = newVideoInput;
            }else{
                [_captureSession addInput:_videoInput];
            }
            [self.videoOutput connectionWithMediaType:AVMediaTypeVideo].videoOrientation = AVCaptureVideoOrientationPortrait;
        } else if (error) {
            NSLog(@"切换前/后摄像头失败, error = %@", error);
        }
    }];
    
    
}
- (IBAction)shanguangAction:(UIButton *)sender {
    BOOL con1 = [_videoDevice hasTorch];    //支持手电筒模式
    BOOL con2 = [_videoDevice hasFlash];    //支持闪光模式
    
    if (con1 && con2)
    {
        [self changeDevicePropertySafety:^(AVCaptureDevice *captureDevice) {
            if (_videoDevice.flashMode == AVCaptureFlashModeOn)         //闪光灯开
            {
                [_videoDevice setFlashMode:AVCaptureFlashModeOff];
                [_videoDevice setTorchMode:AVCaptureTorchModeOff];
            }else if (_videoDevice.flashMode == AVCaptureFlashModeOff)  //闪光灯关
            {
                [_videoDevice setFlashMode:AVCaptureFlashModeOn];
                [_videoDevice setTorchMode:AVCaptureTorchModeOn];
            }
            //            else{                                                      //闪光灯自动
            //                [_videoDevice setFlashMode:AVCaptureFlashModeAuto];
            //                [_videoDevice setTorchMode:AVCaptureTorchModeAuto];
            //            }
            NSLog(@"现在的闪光模式是AVCaptureFlashModeOn么?是你就扣1, %zd",_videoDevice.flashMode == AVCaptureFlashModeOn);
        }];
        sender.selected=!sender.isSelected;
    }else{
        NSLog(@"不能切换闪光模式");
    }
}
// 静态图像输出
- (AVCaptureStillImageOutput *)stillImageOutput
{
    if (_stillImageOutput == nil) {
        _stillImageOutput = [[AVCaptureStillImageOutput alloc] init];
        NSDictionary *outputSettings = [[NSDictionary alloc] initWithObjectsAndKeys:AVVideoCodecJPEG,AVVideoCodecKey,nil];
        _stillImageOutput.outputSettings = outputSettings;
    }
    return _stillImageOutput;
}
// 连接
- (AVCaptureConnection *)imageConnection
{
    AVCaptureConnection *imageConnection = nil;
    for (AVCaptureConnection *connection in self.stillImageOutput.connections) {
        for (AVCaptureInputPort *port in connection.inputPorts) {
            if ([[port mediaType] isEqual:AVMediaTypeVideo]) {
                imageConnection = connection;
                break;
            }
        }
        if (imageConnection) {
            break;
        }
    }
    return imageConnection;
}

#pragma  mark 拍照
- (IBAction)StartShootingAction:(UIButton *)sender {
    [self.stillImageOutput captureStillImageAsynchronouslyFromConnection:[self imageConnection] completionHandler:^(CMSampleBufferRef imageDataSampleBuffer, NSError *error) {
        dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            if (!error) {
                if (imageDataSampleBuffer == NULL) {
                    return;
                }
                NSData * imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];
                UIImage * image = [UIImage imageWithData:imageData];
                dispatch_async(dispatch_get_main_queue(), ^{
                    //                    [AppDelegate shareDelegate].dttype = 2;
                    _clipImage = [UIImage fixOrientation:image];
                    [UserDefaults writeUserDefaultObjectValue:@"0" withKey:@"isship"];
                    UIImageWriteToSavedPhotosAlbum(_clipImage, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
                });
                
            } else {
                //相机初始化错误
            }
            
        });
        
    }];
    
}
#pragma  mark 保存图片至相册回调
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo{
    if (error == nil) {
        [self showPZSubmitBtns];
    }else{
        [SVProgressHUD showImage:nil status:@"保存相册失败"];
    }
}

#pragma mark - 显示确认和取消拍照的按钮
- (void)showPZSubmitBtns {
    _psCenterBtn.userInteractionEnabled = NO;
    _psLeftBtn.hidden = YES;
    _psBackBtn.hidden = NO;
    _psRightBtn.hidden = YES;
    _psSumitBtn.hidden = NO;
    
    _tukuImg.image = _clipImage;
    _tukuImg.hidden = NO;
}
#pragma mark - 隐藏确认和取消拍照的按钮
- (void)hidePZSubmitBtns {
    _psCenterBtn.userInteractionEnabled = YES;
    _psLeftBtn.hidden = NO;
    _psBackBtn.hidden = YES;
    _psRightBtn.hidden = NO;
    _psSumitBtn.hidden = YES;
    
    
    //还原图片显示视图
    ALAsset *result = [Timeimagedata firstObject];
    ALAssetRepresentation *presentation = [result defaultRepresentation];
    CGImageRef resolutionImg = [presentation fullResolutionImage];
    UIImage *img = [UIImage imageWithCGImage:resolutionImg scale:1 orientation:(NSInteger)presentation.orientation];
    imgurl = [presentation.url absoluteString];
    iamgeData = img;
    self.tukuImg.image = img;
    self.tukuImg.hidden = YES;
}

#pragma mark - 完成拍照
- (void)completePZ {
    
    //xhw2018-1-2加:如果是单聊跳转过来的就不用跳到选择封面的Ctrl了
    if (self.InType == 2) {
        if (self.delegate && [self.delegate respondsToSelector:@selector(didGetImage:)]) {
//            __weak __typeof(self)weakSelf = self;
//            [weakSelf.delegate didGetImage:_clipImage];
//            [weakSelf dismissViewControllerAnimated:YES completion:nil];
//            weakSelf.delegate = nil;
            [self.delegate didGetImage:_clipImage];
            [self dismissViewControllerAnimated:YES completion:nil];
            return;
        }
    }
    self.editImageController.image = _clipImage;
    self.editImageController.backVCCount = 1;
    //(xhw11月24号加)
    self.editImageController.InType = self.InType;
    self.editImageController.presentVC = self;
    [self presentViewController:self.editImageController animated:NO completion:nil];
    [self hidePZSubmitBtns];
}

#pragma mark - 取消重新拍照
- (void)cancelPZ {
    [self hidePZSubmitBtns];
}

#pragma  mark 完成拍摄
- (void)completeAction {
    //确认完成
    if (self.currentRecordTime>0) {
        [self stopCaptureHandler:^(UIImage *movieImage) {
            //xhw11月24号加
            if (_InType == 1) {  //从动态跳转过来的
                [self xhwFromDynamicCompleteVideo];
                
            }
            //xhw2018-1-2加: //如果是聊天界面来的
            else if (_InType == 2) {
                [self xhwChatCompleteVideo];
            }
            else {
                [self showCompleteVideo];
            }
//            [self showCompleteVideo];
            //返回重新拍摄状态
            self.spBackBtn.hidden = YES;
            self.spSumitBtn.hidden = YES;
            self.spLeftBtn.hidden = NO;
            self.spRightBtn.hidden = NO;
        }];
    }
}
//从动态跳转过来的话，跳到选择封面界面(xhw11月24号加)
- (void)xhwFromDynamicCompleteVideo {
    //选择封面
    YSHYClipViewController * clipView = [[YSHYClipViewController alloc]initWithImage:[self getVideoPreViewImage:[NSURL fileURLWithPath:self.videoPath]]];
    clipView.delegate = self;
    clipView.xhwType = 2;
    clipView.InType = 1;
    clipView.presentVC = self;
    clipView.clipType = SQUARECLIP; //支持圆形:CIRCULARCLIP 方形裁剪:SQUARECLIP   默认:圆形裁剪
    clipView.radius = SCRE_WIDTH/2.0;   //设置 裁剪框的半径  默认120
    [self presentViewController:clipView animated:YES completion:nil];
}
- (void)xhwChatCompleteVideo {
    [self dismissViewControllerAnimated:YES completion:nil];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"addvideoOfChat" object:[NSURL fileURLWithPath:self.videoPath]];
}

#pragma  mark 取消拍摄
- (void)cancelAction {
    if (self.currentRecordTime>0) {
        [self stopCaptureHandler:^(UIImage *movieImage) {
            //返回重新拍摄
            self.spBackBtn.hidden = YES;
            self.spSumitBtn.hidden = YES;
            self.spLeftBtn.hidden = NO;
            self.spRightBtn.hidden = NO;
        }];
    }
}

#pragma mark 录制相关
- (NSURL *)outPutFileURL
{
    return [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@%@", NSTemporaryDirectory(), @"outPut.mov"]];
}
//开始录制
- (void) startCapture {
    @synchronized(self) {
        if (!self.isCapturing) {
            //            NSLog(@"开始录制");
            self.recordEncoder = nil;
            self.isPaused = NO;
            self.discont = NO;
            _timeOffset = CMTimeMake(0, 0);
            self.isCapturing = YES;
        }
    }
}
//暂停录制
- (void) pauseCapture {
    @synchronized(self) {
        if (self.isCapturing) {
            //            NSLog(@"暂停录制");
            self.isPaused = YES;
            self.discont = YES;
        }
    }
}
//继续录制
- (void) resumeCapture {
    @synchronized(self) {
        if (self.isPaused) {
            //            NSLog(@"继续录制");
            self.isPaused = NO;
        }
    }
}
//停止录制
- (void) stopCaptureHandler:(void (^)(UIImage *movieImage))handler {
    @synchronized(self) {
        if (self.isCapturing) {
            NSString* path = self.recordEncoder.path;
            NSURL* url = [NSURL fileURLWithPath:path];
            self.isCapturing = NO;
            dispatch_async(_captureQueue, ^{
                [self.recordEncoder finishWithCompletionHandler:^{
                    self.isCapturing = NO;
                    self.recordEncoder = nil;
                    self.startTime = CMTimeMake(0, 0);
                    self.currentRecordTime = 0;
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [self resetProViewProgress];
                    });
                    [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
                        [PHAssetChangeRequest creationRequestForAssetFromVideoAtFileURL:url];
                    } completionHandler:^(BOOL success, NSError * _Nullable error) {
                        NSLog(@"保存成功");
                        if (self.InType == 2) {
                            if (self.delegate && [self.delegate respondsToSelector:@selector(didGetVideoWithUrl:videoData:)]) {
                                
                                
                                [self.delegate didGetVideoWithUrl:[NSURL URLWithString:self.videoPath] videoData:[NSData dataWithContentsOfURL:[NSURL URLWithString:self.videoPath]]];
                                [self dismissViewControllerAnimated:YES completion:nil];
                                
                            }
                        }
                    }];
                    [self movieToImageHandler:handler];
                }];
            });
        }
    }
}

//获取视频第一帧的图片
- (void)movieToImageHandler:(void (^)(UIImage *movieImage))handler {
    NSURL *url = [NSURL fileURLWithPath:self.videoPath];
    AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:url options:nil];
    AVAssetImageGenerator *generator = [[AVAssetImageGenerator alloc] initWithAsset:asset];
    generator.appliesPreferredTrackTransform = TRUE;
    CMTime thumbTime = CMTimeMakeWithSeconds(0, 60);
    generator.apertureMode = AVAssetImageGeneratorApertureModeEncodedPixels;
    AVAssetImageGeneratorCompletionHandler generatorHandler =
    ^(CMTime requestedTime, CGImageRef im, CMTime actualTime, AVAssetImageGeneratorResult result, NSError *error){
        if (result == AVAssetImageGeneratorSucceeded) {
            UIImage *thumbImg = [UIImage imageWithCGImage:im];
            if (handler) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    handler(thumbImg);
                });
            }
        }
    };
    [generator generateCGImagesAsynchronouslyForTimes:
     [NSArray arrayWithObject:[NSValue valueWithCMTime:thumbTime]] completionHandler:generatorHandler];
}
- (void)recordComplete
{
    self.canSave = YES;
}

//这个在完全退出小视频时调用
- (void)quit
{
    [_captureSession stopRunning];
}


-(void)dtback{
    [self.navigationController popViewControllerAnimated:YES];
}

//更改设备属性前一定要锁上
-(void)changeDevicePropertySafety:(void (^)(AVCaptureDevice *captureDevice))propertyChange{
    //也可以直接用_videoDevice,但是下面这种更好
    AVCaptureDevice *captureDevice= [_videoInput device];
    NSError *error;
    //注意改变设备属性前一定要首先调用lockForConfiguration:调用完之后使用unlockForConfiguration方法解锁,意义是---进行修改期间,先锁定,防止多处同时修改
    BOOL lockAcquired = [captureDevice lockForConfiguration:&error];
    if (!lockAcquired) {
        NSLog(@"锁定设备过程error，错误信息：%@",error.localizedDescription);
    }else{
        [_captureSession beginConfiguration];
        propertyChange(captureDevice);
        [captureDevice unlockForConfiguration];
        [_captureSession commitConfiguration];
    }
}

- (IBAction)backAction:(UIButton *)sender {
    [AppDelegate shareDelegate].dttype = 0;
    [AppDelegate shareDelegate].islod = NO;
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark - 写入数据
- (void) captureOutput:(AVCaptureOutput *)captureOutput didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection {
    BOOL isVideo = YES;
    @synchronized(self) {
        if (!self.isCapturing  || self.isPaused) {
            return;
        }
        if (captureOutput != self.videoOutput) {
            isVideo = NO;
        }
        
        //初始化编码器，当有音频和视频参数时创建编码器
        if ((self.recordEncoder == nil) && !isVideo)
        {
            CMFormatDescriptionRef fmt = CMSampleBufferGetFormatDescription(sampleBuffer);
            [self setAudioFormat:fmt];
            NSString *videoName = [self getUploadFile_type:@"video" fileTypeName:@"mp4"];
            self.videoPath = [[self getVideoCachePath] stringByAppendingPathComponent:videoName];
            self.recordEncoder = [WCLRecordEncoder encoderForPath:self.videoPath Height:_cy width:_cx channels:_channels samples:_samplerate];
        }
        
        //判断是否中断录制过
        if (self.discont) {
            if (isVideo) {
                return;
            }
            self.discont = NO;
            // 计算暂停的时间
            CMTime pts = CMSampleBufferGetPresentationTimeStamp(sampleBuffer);
            CMTime last = isVideo ? _lastVideo : _lastAudio;
            if (last.flags & kCMTimeFlags_Valid) {
                if (_timeOffset.flags & kCMTimeFlags_Valid) {
                    pts = CMTimeSubtract(pts, _timeOffset);
                }
                CMTime offset = CMTimeSubtract(pts, last);
                if (_timeOffset.value == 0) {
                    _timeOffset = offset;
                }else {
                    _timeOffset = CMTimeAdd(_timeOffset, offset);
                }
            }
            _lastVideo.flags = 0;
            _lastAudio.flags = 0;
        }
        // 增加sampleBuffer的引用计时,这样我们可以释放这个或修改这个数据，防止在修改时被释放
        CFRetain(sampleBuffer);
        if (_timeOffset.value > 0) {
            CFRelease(sampleBuffer);
            //根据得到的timeOffset调整
            sampleBuffer = [self adjustTime:sampleBuffer by:_timeOffset];
        }
        // 记录暂停上一次录制的时间
        CMTime pts = CMSampleBufferGetPresentationTimeStamp(sampleBuffer);
        CMTime dur = CMSampleBufferGetDuration(sampleBuffer);
        if (dur.value > 0) {
            pts = CMTimeAdd(pts, dur);
        }
        if (isVideo) {
            _lastVideo = pts;
        }else {
            _lastAudio = pts;
        }
    }
    CMTime dur = CMSampleBufferGetPresentationTimeStamp(sampleBuffer);
    if (self.startTime.value == 0) {
        self.startTime = dur;
    }
    CMTime sub = CMTimeSubtract(dur, self.startTime);
    self.currentRecordTime = CMTimeGetSeconds(sub);
    if (self.currentRecordTime > self.maxRecordTime) {
        if (self.currentRecordTime - self.maxRecordTime < 0.1) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [self resetProViewProgress];
            });
        }
        return;
    }
    dispatch_async(dispatch_get_main_queue(), ^{
        [self resetProViewProgress];
    });
    // 进行数据编码
    [self.recordEncoder encodeFrame:sampleBuffer isVideo:isVideo];
    CFRelease(sampleBuffer);
}

//设置音频格式
- (void)setAudioFormat:(CMFormatDescriptionRef)fmt {
    const AudioStreamBasicDescription *asbd = CMAudioFormatDescriptionGetStreamBasicDescription(fmt);
    _samplerate = asbd->mSampleRate;
    _channels = asbd->mChannelsPerFrame;
    
}

//调整媒体数据的时间
- (CMSampleBufferRef)adjustTime:(CMSampleBufferRef)sample by:(CMTime)offset {
    CMItemCount count;
    CMSampleBufferGetSampleTimingInfoArray(sample, 0, nil, &count);
    CMSampleTimingInfo* pInfo = malloc(sizeof(CMSampleTimingInfo) * count);
    CMSampleBufferGetSampleTimingInfoArray(sample, count, pInfo, &count);
    for (CMItemCount i = 0; i < count; i++) {
        pInfo[i].decodeTimeStamp = CMTimeSubtract(pInfo[i].decodeTimeStamp, offset);
        pInfo[i].presentationTimeStamp = CMTimeSubtract(pInfo[i].presentationTimeStamp, offset);
    }
    CMSampleBufferRef sout;
    CMSampleBufferCreateCopyWithNewTiming(nil, sample, count, pInfo, &sout);
    free(pInfo);
    return sout;
}

- (EditImageController *)editImageController {
    if (!_editImageController) {
        _editImageController = [[EditImageController alloc]init];
        if (self.delegate && [self.delegate respondsToSelector:@selector(didGetImage:)]) {
            __weak __typeof(self)weakSelf = self;
            _editImageController.commitImage = ^(UIImage *image) {
                [weakSelf.delegate didGetImage:image];
                [weakSelf dismissViewControllerAnimated:YES completion:nil];
                weakSelf.delegate = nil;
            };
        }
        
    }
    return _editImageController;
}

- (IBAction)back:(id)sender {
    [AppDelegate shareDelegate].dttype = 0;
    [self dismissViewControllerAnimated:YES completion:nil];
//    [self.navigationController popViewControllerAnimated:YES]; （xhw11月28注释，本来这句话就没用，之前明明是present出来的）
}


-(void)dealloc {
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
    _captureQueue     = nil;
    
    _audioOutput      = nil;
    _videoOutput      = nil;
    
}
//视频输出
- (AVCaptureVideoDataOutput *)videoOutput {
    if (_videoOutput == nil) {
        _videoOutput = [[AVCaptureVideoDataOutput alloc] init];
        [_videoOutput setSampleBufferDelegate:self queue:self.captureQueue];
        NSDictionary* setcapSettings = [NSDictionary dictionaryWithObjectsAndKeys:
                                        [NSNumber numberWithInt:kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange], kCVPixelBufferPixelFormatTypeKey,
                                        nil];
        _videoOutput.videoSettings = setcapSettings;
    }
    return _videoOutput;
}

//音频输出
- (AVCaptureAudioDataOutput *)audioOutput {
    if (_audioOutput == nil) {
        _audioOutput = [[AVCaptureAudioDataOutput alloc] init];
        [_audioOutput setSampleBufferDelegate:self queue:self.captureQueue];
    }
    return _audioOutput;
}
//录制的队列
- (dispatch_queue_t)captureQueue {
    if (_captureQueue == nil) {
        _captureQueue = dispatch_queue_create("cn.qiuyouqun.im.wclrecordengine.capture", DISPATCH_QUEUE_SERIAL);
    }
    return _captureQueue;
}

//获得视频存放地址
- (NSString *)getVideoCachePath {
    NSString *videoCache = [NSTemporaryDirectory() stringByAppendingPathComponent:@"videos"] ;
    BOOL isDir = NO;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL existed = [fileManager fileExistsAtPath:videoCache isDirectory:&isDir];
    if ( !(isDir == YES && existed == YES) ) {
        [fileManager createDirectoryAtPath:videoCache withIntermediateDirectories:YES attributes:nil error:nil];
    };
    return videoCache;
}
- (NSString *)getUploadFile_type:(NSString *)type fileTypeName:(NSString *)fileTypeName {
    NSTimeInterval now = [[NSDate date] timeIntervalSince1970];
    NSDateFormatter * formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"HHmmss"];
    NSDate * NowDate = [NSDate dateWithTimeIntervalSince1970:now];
    ;
    NSString * timeStr = [formatter stringFromDate:NowDate];
    NSString *fileName = [NSString stringWithFormat:@"%@_%@.%@",type,timeStr,fileTypeName];
    return fileName;
}

- (void)resetProViewProgress {
    //进度条
    pro.progress = self.currentRecordTime/self.maxRecordTime;
    timelable.text = [NSString stringWithFormat:@"%.1f秒",self.currentRecordTime];
    self.spBackBtn.hidden = NO;
    self.spSumitBtn.hidden = NO;
    self.spLeftBtn.hidden = YES;
    self.spRightBtn.hidden = YES;
    
    if (self.currentRecordTime >= self.maxRecordTime) {
        //停止
        [self stopCaptureHandler:^(UIImage *movieImage) {
            [self showCompleteVideo];
        }];
    }
}
#pragma mark - 查看拍的视频
- (void)showCompleteVideo {
    UIStoryboard *customerStoryboard = [UIStoryboard storyboardWithName:@"KP"
                                                                 bundle:[NSBundle mainBundle]];
    VideoCompleteVC *viewcv = [customerStoryboard instantiateViewControllerWithIdentifier:@"VideoCompleteVC"];
    viewcv.videoUrl = [NSURL fileURLWithPath:self.videoPath];
    viewcv.data = _videoList;
    viewcv.isadd = YES;
    viewcv.Fullscreen = YES;
    [self presentViewController:viewcv animated:NO completion:nil];
    viewcv.delage = self;
    self.canSave = NO;
    
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(didGetVideoWithUrl:videoData:)]) {
        __weak __typeof(self)weakSelf = self;
        viewcv.commitVideo = ^(NSURL *videoUrl, NSData *videoData) {
            [weakSelf.delegate didGetVideoWithUrl:videoUrl videoData:videoData];
        };
    }
}

// 获取视频第一帧
- (UIImage*) getVideoPreViewImage:(NSURL *)path
{
    AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:path options:nil];
    AVAssetImageGenerator *assetGen = [[AVAssetImageGenerator alloc] initWithAsset:asset];
    
    assetGen.appliesPreferredTrackTransform = YES;
    CMTime time = CMTimeMakeWithSeconds(0.0, 600);
    NSError *error = nil;
    CMTime actualTime;
    CGImageRef image = [assetGen copyCGImageAtTime:time actualTime:&actualTime error:&error];
    UIImage *videoImage = [[UIImage alloc] initWithCGImage:image];
    CGImageRelease(image);
    return videoImage;
}

#pragma mark -YSYDelegate
- (void)ClipViewController:(YSHYClipViewController *)clipViewController FinishClipImage:(UIImage *)editImage param:(NSDictionary *)dic {
    xhwDTVC *present = self.presentVC;
    while (YES) {
        if ([present isKindOfClass:[xhwDTVC class]]) {
            if (present.presentVC) {
                present = present.presentVC;
            }
            else {
                break;
            }
        }
        else {
            if ([present isKindOfClass:[AddFileViewController class]]) {
                AddFileViewController * vc =(AddFileViewController *)present;
                if (vc.presentVC) {
                    present = vc.presentVC;
                }
                else {
                    break;
                }
            }
            else {
                break;
            }
            
        }
    }
    [present dismissViewControllerAnimated:YES completion:nil];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"addvideo" object:[NSURL fileURLWithPath:self.videoPath]];
//    NSMutableDictionary * xhwDic = [[NSMutableDictionary alloc] init];
//    [xhwDic setObject:[NSURL fileURLWithPath:self.videoPath] forKey:@"videoPath"];
//    [xhwDic setObject:editImage forKey:@"image"];
//    [[NSNotificationCenter defaultCenter] postNotificationName:@"addvideo" object:xhwDic];  //xhw2018-2-12改
}

@end
